package com.lzy.managersystem.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.managersystem.mapper.RoleMenuMapper;
import com.lzy.managersystem.pojo.Menu;
import com.lzy.managersystem.pojo.RoleMenu;
import com.lzy.managersystem.service.MenuService;
import com.lzy.managersystem.service.RoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author qq619
 * @description 针对表【sys_role_menu】的数据库操作Service实现
 * @createDate 2022-07-12 21:21:32
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu>
        implements RoleMenuService {

    @Resource
    RoleMenuMapper roleMenuMapper;
    @Resource
    MenuService menuService;

    @Transactional
    @Override
    public void deleteByRoleid(Integer RoleId, List<Integer> ids) {
        // 先删除当前角色id所有的绑定关系
        roleMenuMapper.deleteByRoleId(RoleId);

        // 再把前端传过来的菜单id数组绑定到当前的这个角色id上去
        List<Integer> menuIdsCopy = CollUtil.newArrayList(ids);
        for (Integer menuId : ids) {
            Menu menu = menuService.getById(menuId);
            if (menu.getPid() != null && !menuIdsCopy.contains(menu.getPid())) { // 二级菜单 并且传过来的menuId数组里面没有它的父级id
                // 那么我们就得补上这个父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(RoleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(RoleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }


    }

    @Override
    public List<Integer> selectByroleid(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }
}




